package com.zy.fcs.controller;

import java.io.IOException;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.zy.fcs.service.oss.OssService;
import com.zy.fcs.utils.ZyUtils;

/**
 * 阿里云上传文件，下载文件
 *
 * @author zhanghengchang
 * @date 2018/3/6
 */
@Controller
@RequestMapping("/oss")
public class AliyunOssController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AliyunOssController.class);

    @Autowired
    private OssService ossService;

    /**
     * 获得影像对象url
     *
     * @return oss url
     */
    @PostMapping(value = "/getMedia")
    public String getMedia(@RequestParam Map<String, Object> params, Model model) {
        String uri = (String)params.get("uri");
        String uriDisp = (String)params.get("uriDisp");

        String[] breadcrumb = uriDisp.split("/");
        String url = ossService.getPreSignedUrl(uri);

        model.addAttribute("breadcrumb", breadcrumb);
        model.addAttribute("mediaUrl", url);
        model.addAttribute("mediaType", ZyUtils.getMediaType(uri));

        return this.render("mediaBody");
    }

    /**
     * 文件Web直传阿里云OSS获得Policy
     *
     * @return oss policy
     * @throws IOException IO异常
     */
    @ResponseBody
    @GetMapping(value = "/getPolicy")
    public String getUploadPolicy(@RequestParam Map<String, Object> params) throws IOException {

        String uploaddir = (String)params.get("uploaddir");
        JSONObject policy = ossService.getUploadPolicy(uploaddir);
        if (policy == null) {
            return "";
        }
        return policy.toString();
    }
}
